from django.shortcuts import render, HttpResponse, redirect, reverse
from App01 import models
from django.views import View
from functools import wraps
from django.utils.decorators import method_decorator


def Login_required(func):
    @wraps(func)
    def inner(request, *args, **kwargs):
        ret = func(request, *args, **kwargs)
        value = request.get_signed_cookie(key='is_login', salt='even', default='')
        if value == 'Y':
            return ret
        else:
            return redirect('/Login/?url={}'.format(request.path_info))
    return inner


def Login(request):
    if request.method == "POST":
        usr = request.POST.get('user')
        pwd = request.POST.get('pwd', None)
        try:
            user_obj = models.User.objects.get(username=usr)
        except Exception:
            return HttpResponse('用户名不正确')
        if user_obj and pwd == user_obj.password:
            url = request.GET.get('url', None)
            print(url)
            if url:
                rep = redirect(url)
            else:
                pub_lis = reverse('pb_lis')
                rep = redirect(pub_lis)
            rep.set_signed_cookie(key='is_login', value='Y', salt='even')
            return rep
        else:
            return HttpResponse('密码不正确')
    return render(request, 'login.html')


def Index(request):
    return render(request, "index.html")


@method_decorator(Login_required, name='get')
class publisher_list(View):
    def get(self, request):
        ret = models.Publisher.objects.all()
        return render(request, 'publisher_list.html', {'publisher_list': ret})


class add_publisher(View):
    def get(self, request):
        return render(request, 'add_publisher.html')

    def post(self, request):
        new_name = request.POST.get('publishername', None)
        if new_name:
            models.Publisher.objects.create(name=new_name)
            URL = reverse('pb_lis')
            return redirect(URL)
        else:
            error_msg = '出版社名称不能为空'
            return render(request, 'add_publisher.html', {'error': error_msg})


# class del_publisher(View):
#     def get(self, _, del_id=None):  # 分组传参,没有用到request用下划线替代位置
#         if del_id:
#             del_obj = models.Publisher.objects.get(id=del_id)
#             del_obj.delete()
#             URL = reverse('pb_lis')
#             return redirect(URL)
#         else:
#             return HttpResponse("要删除的数据不存在!")


class edit_publisher(View):
    def get(self, request, edit_id=None):
        if edit_id:
            publisher_obj = models.Publisher.objects.get(id=edit_id)
            return render(request, "edit_publisher.html", {"publisher": publisher_obj})
        else:
            return HttpResponse("编辑的出版社不存在!")

    def post(self, request):
        edit_id = request.POST.get("id")
        new_name = request.POST.get("publisher_name")
        edit_publisher = models.Publisher.objects.get(id=edit_id)
        edit_publisher.name = new_name
        edit_publisher.save()
        URL = reverse('pb_lis')
        return redirect(URL)


@Login_required
def book_list(request):
    ret = models.Book.objects.all()
    return render(request, 'book_list.html', {'book_list': ret})


def add_book(request):
    if request.method == 'POST':
        new_name = request.POST.get('bookname', None)
        new_publisher = request.POST.get('new_publisher', None)
        new_author = request.POST.getlist("new_author")

        if new_name:
            new_book = models.Book.objects.create(name=new_name, publisher_id=new_publisher)
            new_book.authors.set(new_author)
            return redirect('/book_list/')
        else:
            error_msg = '书籍不能为空'
            all_publisher = models.Publisher.objects.all()
            all_author = models.Author.objects.all()
            return render(request, 'add_book.html',
                          {'error': error_msg, 'publisher_list': all_publisher, "author_list": all_author})
    all_publisher = models.Publisher.objects.all()
    all_author = models.Author.objects.all()
    return render(request, 'add_book.html', {'publisher_list': all_publisher, "author_list": all_author})


# def del_book(request):
#     del_id = request.GET.get("id", None)
#     if del_id:
#         del_obj = models.Book.objects.get(id=del_id)
#         del_obj.delete()
#         return redirect("/book_list/")
#     else:
#         return HttpResponse("要删除的数据不存在!")


def edit_book(request):
    if request.method == "POST":
        edit_id = request.POST.get("id")
        new_name = request.POST.get("book_name")
        new_publisherid = request.POST.get("edit_pub")
        new_author = request.POST.getlist("edit_au")
        edit_book = models.Book.objects.get(id=edit_id)
        edit_book.name = new_name
        edit_book.publisher_id = new_publisherid
        edit_book.authors.set(new_author)
        edit_book.save()
        return redirect("/book_list/")

    edit_id = request.GET.get("id", None)
    if edit_id:
        book_obj = models.Book.objects.get(id=edit_id)
        all_publisher = models.Publisher.objects.all()
        all_author = models.Author.objects.all()
        return render(request, "edit_book.html",
                      {"book": book_obj, "publisher_list": all_publisher, "author_list": all_author})
    else:
        return HttpResponse("编辑的出版社不存在!")


@Login_required
def author_list(request):
    all_author = models.Author.objects.all()
    return render(request, "author_list.html", {"author_list": all_author})


def add_author(request):
    if request.method == "POST":
        new_name = request.POST.get("authorname", None)
        new_books = request.POST.getlist("new_book")
        if new_name:
            new_author = models.Author.objects.create(name=new_name)
            new_author.books.set(new_books)
            return redirect("/author_list/")
        else:
            error_msg = "作者名不能为空"
            all_author = models.Author.objects.all()
            all_book = models.Book.objects.all()
            return render(request, "add_author.html", {"author_list": all_author, "error": error_msg,
                                                       "book_list": all_book})
    all_author = models.Author.objects.all()
    all_book = models.Book.objects.all()
    return render(request, "add_author.html", {"author_list": all_author, "book_list": all_book})


# def del_author(request):
#     del_id = request.GET.get("id", None)
#     if del_id:
#         del_obj = models.Author.objects.get(id=del_id)
#         del_obj.delete()
#         return redirect("/author_list/")
#     else:
#         return HttpResponse("要删除的数据不存在!")


def edit_author(request):
    if request.method == "POST":
        edit_id = request.POST.get("id")
        new_books = request.POST.getlist("edit_books", None)
        new_name = request.POST.get("author_name", None)
        edit_obj = models.Author.objects.get(id=edit_id)
        edit_obj.name = new_name
        edit_obj.books.set(new_books)
        edit_obj.save()
        return redirect("/author_list/")

    edit_id = request.GET.get("id")
    if edit_id:
        edit_obj = models.Author.objects.get(id=edit_id)
        all_book = models.Book.objects.all()
        return render(request, "edit_author.html", {"author": edit_obj, "book_list": all_book})


def del_all(request, table_name, del_id):
    table_name = table_name.capitalize()
    if hasattr(models, table_name):
        table = getattr(models, table_name)
        print(del_id)
        try:
            table.objects.get(id=del_id).delete()
        except Exception:
            return HttpResponse('id不存在')
        return redirect('/{}_list/'.format(table_name.lower()))
    else:
        return HttpResponse('表不存在')
